<?php

App::uses('CakeEmail', 'Network/Email');

class UserController extends AppController {

    public $name = 'User';
    public $uses = array(
        'User', 'CountryProvince', 'CountryDistrict', 'Countryward', 'ActiveCode', 'Order', 'OrderDetail', 'Product', 'ProductLink', 'DownloadCount'
    );

    /*
     * function register new user
     * author: NGuyen Tat Loi
     * date: 26/11/2013
     */

    public function register() {
        $data = $this->request->data;
        if (!empty($data['User'])) {
            $data = $data['User'];
            if (!empty($data['captcha'])) {
                if ($data['captcha'] == $this->Session->read('captcha')) {

                    $this->User->set($this->request->data);
                    if ($this->User->validates()) {
                        if ($data['password'] == $data['re_password']) {
                            if (!$check_username = $this->User->check_exist_username($data['username'])) {
                                if (!$check_email = $this->User->check_exist_email($data['email'])) {
                                    $data['old_password'] = $data['password'];
                                    $data['password'] = md5(md5($data['password']));
                                    //active luon cho khach hang
                                    $data['status'] = 1;
                                    $data['active_key'] = md5(time() . rand(0000, 9999));
                                    if ($this->User->save($data)) {
                                        try {
                                            //Sent email
                                            $emailVar = array(
                                                'username' => $data['username'],
                                                'password' => $data['old_password'],
                                                'email' => $data['email'],
                                                'fullname' => $data['fullname']
                                            );
                                            $Email = new CakeEmail();
                                            $Email->config('default')
                                                    ->template('register')
                                                    ->emailFormat('html')
                                                    ->viewVars($emailVar)
                                                    ->to($data['email'])
                                                    ->subject('Thank you for registering at 3DArcShop')
                                                    ->send();
                                        } catch (Exception $e) {
                                            CakeLog::write('Email-' . date('Y-m-d'), 'Gửi email đăng ký email:' . $data['email'] . " lỗi. Time: " . date('Y-m-d H:i:s'));
                                        }
                                        //Logged user
                                        $this->Session->write('user', $this->User->check_user($data['username'], $data['password']));
                                        $this->Session->setFlash('Register Success');
                                        $this->set('success', 1);
                                    } else {
                                        $this->Session->setFlash('Register Failed. Please try again later');
                                    }
                                } else {
                                    $this->Session->setFlash('Email exist!');
                                }
                            } else {
                                $this->Session->setFlash('Username exist!');
                            }
                        } else {
                            $this->Session->setFlash(' Password Confirm not match!');
                        }
                    }
                } else {
                    $this->Session->setFlash('Please enter the correct captcha code!');
                }
            } else {
                $this->Session->setFlash('You need to enter the captcha code!');
            }
        }
    }

    /*
     * function login to system
     * author: Nguyen Tat Loi
     * date: 26/11/2013
     */

    public function login() {
        //check phan ghi nho dang nhap
        //neu co check ghi nho dang nhap thi luu vao cookie
        $redirect = !empty($this->params->query['redirect']) ? $this->params->query['redirect'] : '/';
        if ($this->Session->read('user')) {
            $this->redirect(array('controller' => 'User', 'action' => 'userinfo'));
        } else {
            if ($this->request->data) {
                $this->User->set($this->request->data);
                $data = $this->request->data['User'];
                $username = $data['username'];
                $password = md5(md5($data['password']));
                if ($check = $this->User->check_user($username, $password)) {
                    $this->Session->write('user', $check);
                    $this->redirect($redirect);
                } else {
                    $this->Session->setFlash('Warning: No match for E-Mail Address and/or Password.');
                }
            }
        }
    }

    /*
     * funciton logout system
     * author: NGuyen Tat Loi
     * date: 26/11/2013
     */

    public function logout() {
        $this->Session->delete('user');
        $this->Session->delete('failed_time');
        $this->Session->delete('shopping_cart');
        $this->redirect($this->referer());
    }

    public function userinfo() {
        if (!$user = $this->Session->read('user')) {
            $this->redirect(array('action' => 'login', '?' => array('redirect' => $this->here)));
        }

        $user_id = $user['User']['id'];

        $list_order = $pending = $this->Order->find('all', array(
            'conditions' => array('Order.user_id' => $user_id),
            'order' => array('Order.created' => 'desc')
                ));
        $this->set('list_order', $list_order);
    }

    /*
     * function show info of user
     * enable users change their information in page
     * author: Nguyen Tat Loi
     * date: 26/11/2013
     */

    public function user_panel() {
        if ($user = $this->Session->read('user')) {
            if (!empty($this->request->data)) {
                //update thong tin
                //unset username + password
                $data = $this->request->data['User'];
                /*
                  if (!empty($data['captcha'])) {
                  if ($data['captcha'] == $this->Session->read('captcha')) {
                 */
                if (!empty($data['username']))
                    unset($data['username']);
                if (!empty($data['email']))
                    unset($data['email']);
                if (!empty($data['password'])) {
                    if ($data['password'] == $data['re_password']) {
                        $data['password'] = md5(md5($data['password']));
                    }
                } else {
                    unset($data['password']);
                }
                $data['id'] = $user['User']['id'];
                if ($this->User->save($data)) {
                    $user = $this->User->findById($user['User']['id']);
                    $this->Session->write('user', $user);
                    $this->Session->setFlash('Update info success !');
                } else {
                    $this->Session->setFlash('Update info fail !');
                }
                /*
                  } else {
                  $this->Session->setFlash('Mã bảo vệ không đúng');
                  }
                  } else {
                  $this->Session->setFlash('Bạn phải nhập mã bảo vệ!');
                  }
                 */
            }
            if (!$province = Cache::read('province')) {
                $province = $this->CountryProvince->find(
                        'list', array(
                    'fields' => array('CountryProvince.id', 'CountryProvince.province_name')
                        )
                );
                Cache::write('province', $province);
            }
            if (!$district = Cache::read('district_' . $user['User']['province_id'])) {
                $district = $this->CountryDistrict->find(
                        'list', array(
                    'fields' => array('CountryDistrict.id', 'CountryDistrict.districts_name'),
                    'conditions' => array('CountryDistrict.province_id' => $user['User']['province_id'])
                        )
                );
                Cache::write('district_' . $user['User']['province_id'], $district);
            }
            $this->set('province', $province);
            $this->set('district', $district);
            $this->set('user', $user['User']);
            $user['User']['password'] = "";
            $this->data = $user;

            $redirect = '/account';
            if (isset($this->request->query['redirect'])) {
                $redirect = $this->request->query['redirect'];
                $redirect .= '?complete=1';
            }
            $this->set('redirect', $redirect);
        } else {
            $this->redirect(array('action' => 'login', '?' => array('redirect' => $this->here)));
        }
    }

    /*
     * function change password
     * author: Nguyen Tat Loi
     * date: 13/6/2014
     */

    public function change_pass() {
        if ($user = $this->Session->read('user')) {
            $data = $this->request->data;
            if (!empty($data['User'])) {
                $data = $data['User'];
                if (!empty($data['captcha'])) {
                    if ($data['captcha'] == $this->Session->read('captcha')) {
                        if (!empty($data['password']) && !empty($data['new_password']) && !empty($data['re_new_password'])) {
                            if ($data['new_password'] == $data['re_new_password']) {
                                $password = md5(md5($data['password']));
                                $new_password = md5(md5($data['new_password']));
                                if ($password == $user['User']['password']) {
                                    $update = array(
                                        'id' => $user['User']['id'],
                                        'password' => $new_password
                                    );
                                    if ($this->User->save($update)) {
                                        $user = $this->User->findById($user['User']['id']);
                                        $this->Session->write('user', $user);
                                        $this->Session->setFlash('Đổi mật khẩu thành công');
                                    } else {
                                        $this->Session->setFlash('Đổi mật khẩu không thành công');
                                    }
                                } else {
                                    $this->Session->setFlash('Mật khẩu cũ không chính xác.');
                                }
                            } else {
                                $this->Session->setFlash('Mật khẩu mới nhập lại không đúng');
                            }
                        } else {
                            $this->Session->setFlash('Bạn phải nhập đầy đủ thông tin.');
                        }
                    } else {
                        $this->Session->setFlash('Mã bảo vệ không đúng');
                    }
                } else {
                    $this->Session->setFlash('Bạn phải nhập mã bảo vệ!');
                }
            }
        } else {
            $this->redirect(array('controller' => 'User', 'action' => 'login', '?' => array('redirect' => $this->here)));
        }
    }

    /*
     * function forgot password
     * author: Nguyen Tat Loi
     * date: 13/6/2014
     */

    public function forgot_pass() {
        if ($user = $this->Session->read('user')) {
            $this->redirect(array('controller' => 'User', 'action' => 'userinfo'));
        }

        $data = $this->request->data;
        if (!empty($data['User'])) {
            $data = $data['User'];
            if (!empty($data['email'])) {
                if (!empty($data['captcha'])) {
                    if ($data['captcha'] == $this->Session->read('captcha')) {
                        if ($check_email = $this->User->check_exist_email($data['email'])) {
                            $key = md5(time() . rand(0000, 9999));
                            $active_code = array(
                                'user_id' => $check_email['User']['id'],
                                'active_code' => $key,
                                'type' => 'forgot_password'
                            );
                            $news_pass = substr($key, 0, 6);
                            $this->ActiveCode->save($active_code);
                            $viewVar = array(
                                'username' => $check_email['User']['username'],
                                'email' => $data['email'],
                                'fullname' => $check_email['User']['fullname'],
                                'active_code' => $key,
                                'news_pass' => $news_pass
                            );
                            //send mail
                            $Email = new CakeEmail();
                            $Email->config('default')
                                    ->template('forgot_password')
                                    ->emailFormat('html')
                                    ->to($data['email'])
                                    ->subject('Forgot password')
                                    ->viewVars($viewVar)
                                    ->send();

                            //notify to user
                            $this->Session->setFlash('Success: A new password has been sent to your e-mail address.');
                        } else {
                            $this->Session->setFlash('Warning: The E-Mail Address was not found in our records, please try again!');
                        }
                    } else {
                    $this->Session->setFlash('Please enter the correct captcha code!');
                }
            } else {
                $this->Session->setFlash('You need to enter the captcha code!');
            }
            } else {
                $this->Session->setFlash('Warning: The E-Mail Address was not found in our records, please try again!');
            }
        }
    }

    /*
     * function lay lai mat khau
     * author: Nguyen Tat Loi
     * date: 17/6/2014
     */

    public function reget_pass($code = null) {
        if (!empty($code)) {
            $active_record = $this->ActiveCode->findByActiveCode($code);
            if (!empty($active_record)) {
                if ($active_record['ActiveCode']['type'] == 'forgot_password') {
                    $password = substr(md5(md5(time() . rand(0000, 9999))), 0, 6);
                    $user_update = array(
                        'id' => $active_record['User']['id'],
                        'password' => md5(md5($password))
                    );
                    if ($this->User->save($user_update)) {
                        $this->ActiveCode->delete($active_record['ActiveCode']['id']);

                        $viewVar = array(
                            'username' => $active_record['User']['username'],
                            'password' => $password,
                            'fullname' => $active_record['User']['fullname'],
                            'email' => $active_record['User']['email']
                        );
                        //send mail
                        $Email = new CakeEmail();
                        $Email->config('default')
                                ->template('reget_password')
                                ->emailFormat('html')
                                ->to($active_record['User']['email'])
                                ->subject('Reset password')
                                ->viewVars($viewVar)
                                ->send();
                        $this->Session->setFlash('Success: A new password has been sent to your email');
                    } else {
                        $this->Session->setFlash('Warning: Update your new password failed. Invites you to try again later');
                    }
                } else {
                    $this->Session->setFlash('Warning: The path is incorrect or has been deleted by admin. Please contact the webmaster for more information');
                }
            } else {
                $this->Session->setFlash('Warning: The path is incorrect or has been deleted by admin. Please contact the webmaster for more information');
            }
        } else {
            $this->Session->setFlash('Warning: The path is incorrect or has been deleted by admin. Please contact the webmaster for more information');
        }
    }

    /*
     * function render captcha
     * author: Nguyen Tat Loi
     * date: 12/6/2014
     */

    public function captcha() {
        $this->autoRender = false;
        $this->autoLayout = false;
        if (!isset($this->Captcha)) {
            $this->Captcha = $this->Components->load('Captcha', array(
                'width' => 130,
                'height' => 35,
                'characters' => 5,
                'theme' => 'default',
                    ));
        }
        $this->Captcha->create();
    }

    /*
     * function check exist username
     * author: Nguyen Tat Loi
     */

    public function check_exist_username() {
        
    }

    /*
     * function check exist email
     * author: NGuyen Tat Loi
     */

    public function check_exist_email() {
        
    }

    /*
     * function get quan huyen theo tinh thanh
     * author: Nguyen Tat Loi
     */

    public function get_district() {
        $this->autoLayout = false;
        $this->autoRender = false;
        $data = $this->request->data;
        if (!empty($data['province_id'])) {
            if (!$district = Cache::read('district_' . $data['province_id'])) {
                $district = $this->CountryDistrict->find(
                        'list', array(
                    'fields' => array('CountryDistrict.id', 'CountryDistrict.districts_name'),
                    'conditions' => array('CountryDistrict.province_id' => $data['province_id'])
                        )
                );
                Cache::write('district_' . $data['province_id'], $district);
            }
            echo json_encode(array('success' => true, 'district' => $district));
        }
    }

    /*
     * function show order detail
     * author: NGuyen Tat Loi
     * date: 30/7/2014
     */

    public function order($id = null) {
        if (!empty($id)) {
            if ($user = $this->Session->read('user')) {
                $check = $this->Order->find(
                        'first', array(
                    'conditions' => array(
                        'Order.id' => $id,
                        'Order.user_id' => $user['User']['id']
                    )
                        )
                );
                if (!empty($check)) {
                    $order_detail = $this->OrderDetail->findAllByOrderId($check['Order']['id']);
                    if (!empty($order_detail)) {
                        $this->set('order', $check);
                        if ($check['Order']['payment_status'] == '1') {
                            foreach ($order_detail as $key => $value) {
                                $order_detail[$key]['ProductLink'] = $this->ProductLink->findAllByProductId($value['Product']['id']);
                            }
                        }
                        $this->set('order_detail', $order_detail);
                    } else {
                        $this->redirect('/');
                    }
                } else {
                    $this->redirect('/');
                }
            } else {
                $this->redirect(array('controller' => 'User', 'action' => 'login', '?' => array('redirect' => $this->here)));
            }
        } else {
            $this->redirect('/');
        }
    }

    public function download() {
        if ($user = $this->Session->read('user')) {
            if (!empty($this->params->query['order_id']) && !empty($this->params->query['product_link_id'])) {
                $user_id = $user['User']['id'];
                $orderId = $this->params->query['order_id'];
                $productLinkId = $this->params->query['product_link_id'];
                $downloadCount = $check = $this->DownloadCount->find(
                        'first', array(
                    'conditions' => array(
                        'DownloadCount.uid' => $user_id,
                        'DownloadCount.order_id' => $orderId,
                        'DownloadCount.product_link_id' => $productLinkId
                    )
                        )
                );
                if ($downloadCount['DownloadCount']['turn_left'] > 0) {
                    $linkFile = $this->ProductLink->find(
                            'first', array(
                        'conditions' => array(
                            'ProductLink.id' => $productLinkId
                        )
                            )
                    );
                    $count = array(
                        'id' => $downloadCount['DownloadCount']['id'],
                        'turn_left' => $downloadCount['DownloadCount']['turn_left'] - 1
                    );
                    $quickKey = $linkFile['ProductLink']['link_href'];
                    $appId = Configure::read('MFApi.appid');
                    $apiKey = Configure::read('MFApi.apikey');
                    $email = Configure::read('MFApi.email');
                    $password = Configure::read('MFApi.password');
                    App::import('Vendor', 'mflib', array('file' => 'mflib.php'));
                    $mflib = new mflib($appId, $apiKey);
                    $mflib->email = $email;
                    $mflib->password = $password;
                    $sessionToken = $mflib->userGetSessionToken();
                    $result = $mflib->fileGetLinks($quickKey, 'direct_download', $sessionToken);
                    if (isset($result['links'][0]['direct_download'])) {
                        $date = date('Y-m-d');
                        CakeLog::write("Downloaded" . $date, "Trang thai download: " . $result['result'] . " - id: " . $user_id . " - Email: " . $user['User']['email'] . " - Username: " . $user['User']['username'] . " - OrderId:" . $orderId . " - Quick key:" . $quickKey . " - ProductLinkId:" . $productLinkId . " \r\n");
                        $this->DownloadCount->save($count);
                        header("Location:" . $result['links'][0]['direct_download']);
                    } else {
                        $this->redirect('/');
                    }
                } else {
                    echo '<script>alert("File download fail!. You can only download this file 2 times."); location.href="/account";</script>';
                    die;
                }
                exit;
            } else {
                $this->redirect('/');
            }
        } else {
            $this->redirect(array('controller' => 'User', 'action' => 'login', '?' => array('redirect' => $this->here)));
        }
    }

}

?>